package com.kkd.kkdapp.activity;

import java.text.DecimalFormat;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kkd.kkdapp.Environment;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.AccountInfoRes;
import com.kkd.kkdapp.http.entity.BondTransferParData;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AuthenticationUtils;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.view.KkdListHeader;
import com.kkd.kkdapp.view.ScrollerLayout;
import com.kkd.kkdapp.view.EditText.FinanceEditText;
import com.kkd.kkdapp.view.EditText.FinanceEditText.onFinanceEditListener;
import com.kkd.kkdapp.view.ScrollerLayout.OnPullListener;
import com.kkd.kkdapp.view.ScrollerLayout.ScrollStateProvider;
import com.kkd.kkdapp.view.xlistview.XListViewHeader;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;

/******
 * 
 * 债权购买
 * 
 * @author mty
 * 
 */
public class CreditorIsRightsTenderAffirmActivity extends BaseActivity
		implements OnClickListener {

	private static final int ACCOUNTINFO_CODE_ZERO = 1; // 账户余额code=0
	private static final int ACCOUNTINFO_CODE_ELSE = 2; // 账户余额code=其它
	private static final int TENDER_CODE_ZERO = 3; // 投标code=0
	private static final int TENDER_CODE_ELSE = 4; // 投标code=其它
	private static final int PARTICULARS_CODE_ZERO = 5; // 债权详情code=0
	private static final int PARTICULARS_CODE_ELSE = 6; // 债权详情code=其它
	private static final int TENDER_REQUESTCODE = 100;

	private RelativeLayout affirm_title_img; // 返回键
	private Button next_bt; // 投标按钮
	private BondTransferParData data;
	private TextView eachPrice_tv; // 每份价格
	private DecimalFormat df = new DecimalFormat("0.01");
	private TextView term_tv1, term_tv2; // 剩余期限
	private TextView purchase_amount; // 剩余份数
	private TextView expected_tv; // 预期年化收益率
	private FinanceEditText invest_ed; // 输入框
	private TextView buyAll_bt; // 全购
	private double balance; // 账户余额
	private Dialog loadDialog;
	private AccountInfoRes mAccountInfo;
	private TextView balance_tv; // 账户余额
	private TextView buyamount_tv; // 购买金额
	private TextView estimate_tv; // 预计赚得收益
	private TextView financial_agreement_tv2; // 债权转让协议
	private Dialog nsfDialog; // 账户余额不足对话框
	private Dialog mSinaDialog;
	private String loading = "正在购买,请稍候......";
	private Dialog tenderDialog; // 投标等待Dialog
	private Dialog beDefeatedDialog;// 投标失败结果Dialog
	private String json;
	private ScrollerLayout mScrollView;
	private KkdListHeader mHeaderView;
	private ScrollView nScrollView;
	private TextView recharge; // 充值
	private RelativeLayout frozen_popup; // icon
	private PopupWindow tip_popupWindow;
	private TextView title_tv; // 标题
	private ImageView frozen_img;
	private RelativeLayout null_ll; // 已售馨

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case ACCOUNTINFO_CODE_ZERO:
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				balance_tv.setText(df.format(balance));
				if (mAccountInfo.getWithholdAuth().getWithdrawStatus() == 1) {
					showSinaDialog();
				}
				break;
			case ACCOUNTINFO_CODE_ELSE:
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				String desc = (String) msg.obj;
				showToast(desc);
				break;
			case TENDER_CODE_ZERO:
				closeTenderToLoadDialog();
				String str = msg.obj.toString();
				try {
					JSONObject jsonStr = new JSONObject(str);
					String repaymentType = jsonStr.getString("repaymentType");
					String nextCollectDate = jsonStr
							.getString("nextCollectDate");
					String startInterest = jsonStr.getString("startInterest");
					String poiId = jsonStr.getString("poiId");
					int productType = jsonStr.getInt("productType");
					Intent intent = new Intent(
							CreditorIsRightsTenderAffirmActivity.this,
							CreditorIsRightsTenderAffirmSuccessActivity.class);
					intent.putExtra("json", json);
					intent.putExtra("repaymentType", repaymentType);
					intent.putExtra("nextCollectDate", nextCollectDate);
					intent.putExtra("buyAmount", buyamount_tv.getText()
							.toString());
					intent.putExtra("buynumber", invest_ed.getText().toString());
					intent.putExtra("estimate", estimate_tv.getText()
							.toString());
					intent.putExtra("startInterest", startInterest);
					intent.putExtra("poiId", poiId);
					intent.putExtra("productType", productType);
					startActivityForResult(intent, TENDER_REQUESTCODE);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				break;
			case TENDER_CODE_ELSE:
				closeTenderToLoadDialog();
				showTenderBeDefeatedResult(msg.obj.toString());
				next_bt.setEnabled(true);
				next_bt.setClickable(true);
				break;
			case PARTICULARS_CODE_ZERO:
				data = (BondTransferParData) msg.obj;
				if (data.getLeftCount() == 0) {
					null_ll.setVisibility(View.VISIBLE);
					mScrollView.setVisibility(View.GONE);
				} else {
					null_ll.setVisibility(View.GONE);
					mScrollView.setVisibility(View.VISIBLE);
				}
				purchase_amount.setText("" + data.getLeftCount());
				invest_ed.setText("");
				invest_ed.setHint("最多可购买" + data.getLeftCount() + "份");
				mScrollView.clearState();
				break;
			case PARTICULARS_CODE_ELSE:
				String descStr = (String) msg.obj;
				showToast(descStr);
				mScrollView.clearState();
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_creditor_is_rights_tender_affirm);
		initView();
		setListener();
		getMessge();
		inputProcessing();
	}

	/****
	 * 初始化控件
	 */
	public void initView() {
		affirm_title_img = (RelativeLayout) this
				.findViewById(R.id.affirm_title_img);
		next_bt = (Button) this.findViewById(R.id.next_bt);
		eachPrice_tv = (TextView) this.findViewById(R.id.eachPrice_tv);
		term_tv1 = (TextView) this.findViewById(R.id.term_tv1);
		term_tv2 = (TextView) this.findViewById(R.id.term_tv2);
		purchase_amount = (TextView) this.findViewById(R.id.purchase_amount);
		expected_tv = (TextView) this.findViewById(R.id.expected_tv);
		invest_ed = (FinanceEditText) this.findViewById(R.id.invest_ed);
		invest_ed.setDecimalDigits(0);
		buyAll_bt = (TextView) this.findViewById(R.id.buyAll_bt);
		balance_tv = (TextView) this.findViewById(R.id.balance_tv);
		buyamount_tv = (TextView) this.findViewById(R.id.buyamount_tv);
		estimate_tv = (TextView) this.findViewById(R.id.estimate_tv);
		title_tv = (TextView) this.findViewById(R.id.title_tv);
		financial_agreement_tv2 = (TextView) this
				.findViewById(R.id.financial_agreement_tv2);
		recharge = (TextView) findViewById(R.id.recharge);
		frozen_popup = (RelativeLayout) this.findViewById(R.id.frozen_popup);
		frozen_img = (ImageView) this.findViewById(R.id.frozen_img);
		null_ll = (RelativeLayout) this.findViewById(R.id.null_ll);
		nScrollView = (ScrollView) findViewById(R.id.childScroll);
		mScrollView = (ScrollerLayout) findViewById(R.id.mScrollView);
		mHeaderView = new KkdListHeader(this);
		mScrollView.addTopView(mHeaderView);
		mScrollView.setScrollStateProvider(new ScrollStateProvider() {

			@Override
			public boolean canPullUp() {
				return false;
			}

			@Override
			public boolean canPullDown() {
				int scrollY = nScrollView.getScrollY();
				if (scrollY == 0) {
					return true;
				}
				return false;
			}
		});
		mScrollView.setOnPullListener(new OnPullListener() {

			@Override
			public void onPullUp(float pull) {

			}

			@Override
			public void onPullStateChange(byte state) {
				switch (state) {
				case ScrollerLayout.STATUS_IDLE:// 空闲状态
					mHeaderView.setVisibility(View.GONE);
					break;
				case ScrollerLayout.STATUS_PULL_DOWN:// 下拉：不满足hold条件
					mHeaderView.setVisibility(View.VISIBLE);
					mHeaderView.setState(XListViewHeader.STATE_NORMAL);
					break;
				case ScrollerLayout.STATUS_PULL_UP:// 上拉：不满足hold条件
					break;
				case ScrollerLayout.STATUS_UP_HOLD:// 上拉后等待状态
					break;
				case ScrollerLayout.STATUS_DOWN_HOLD:// 下拉后等待状态
					mHeaderView.setState(XListViewHeader.STATE_REFRESHING);
					getAccountInfo();
					requestParticulars();
					break;
				case ScrollerLayout.STATUS_ANIMATING:// 回弹动画状态
					break;
				case ScrollerLayout.STATUS_PULL_DOWN_ENABLE:// 下拉：满足hold条件，松开将hold
					mHeaderView.setState(XListViewHeader.STATE_READY);
					break;
				case ScrollerLayout.STATUS_PULL_UP_ENABLE: // 上拉：满足hold条件，松开将hold
					break;
				default:
					break;
				}
			}

			@Override
			public void onPullDown(float pull) {

			}
		});
	}

	/***
	 * 获取上个界面传值
	 */
	public void getMessge() {
		Intent intent = this.getIntent();
		json = intent.getStringExtra("json");
		LogUtil.e("TAg", "购买json--->" + json);
		Gson gson = new Gson();
		data = gson.fromJson(json, new TypeToken<BondTransferParData>() {
		}.getType());
		dataLoading();
	}

	/******
	 * 数据加载
	 */
	public void dataLoading() {
		if (data.getLeftCount() == 0) {
			null_ll.setVisibility(View.VISIBLE);
			mScrollView.setVisibility(View.GONE);
		} else {
			null_ll.setVisibility(View.GONE);
			mScrollView.setVisibility(View.VISIBLE);
		}
		// 标题
		String title = data.getTitle();
		title_tv.setText(title);
		// 每份价格
		eachPrice_tv.setText(df.format(data.getPerAmount() * 0.01));
		// 剩余期限
		int leftTermMont = data.getLeftTermMonthDesc();
		int leftTermDayDesc = data.getLeftTermDayDesc();
		if (leftTermMont != 0 && leftTermDayDesc != 0) {
			term_tv1.setText("" + leftTermMont);
			term_tv2.setText("个月" + leftTermDayDesc + "天");
		} else if (leftTermMont == 0) {
			term_tv1.setText("" + leftTermDayDesc);
			term_tv2.setText("天");
		} else if (leftTermDayDesc == 0) {
			term_tv1.setText("" + leftTermMont);
			term_tv2.setText("个月");
		} else if (leftTermMont == 0 && leftTermDayDesc == 0) {
			term_tv1.setText("" + leftTermMont);
			term_tv2.setText("个月" + leftTermDayDesc + "天");
		}
		// 剩余份数
		int leftCount = data.getLeftCount();
		purchase_amount.setText("" + leftCount);
		// 预期年化收益率
		String perYearRateDisplay = data.getPerYearRateDisplay();
		String activityRateDisplay = data.getActivityRateDisplay();
		if (activityRateDisplay != null && !"".equals(activityRateDisplay)) {
			expected_tv.setText(df.format(Double
					.parseDouble(perYearRateDisplay)
					+ Double.parseDouble(activityRateDisplay)) + "%");
		} else {
			expected_tv.setText(df.format(perYearRateDisplay) + "%");
		}
		// 最多购买个数
		invest_ed.setHint("最多可购买" + leftCount + "份");
		invest_ed.setLimitMax(leftCount);
	}

	/*****
	 * 注册监听事件
	 */
	public void setListener() {
		affirm_title_img.setOnClickListener(this);
		next_bt.setOnClickListener(this);
		buyAll_bt.setOnClickListener(this);
		financial_agreement_tv2.setOnClickListener(this);
		recharge.setOnClickListener(this);
		frozen_popup.setOnClickListener(this);
		invest_ed.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					if (next_bt.isEnabled())
						tender();
				}
				return false;
			}
		});
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.affirm_title_img: // 后退键
			finish();
			break;
		case R.id.next_bt: // 投标按钮
			tender();
			break;
		case R.id.buyAll_bt: // 全购
			if (data != null) {
				Toast.makeText(this, "已自动填入可购最大份数", Toast.LENGTH_SHORT).show();
				invest_ed.setText("" + data.getLeftCount());
				invest_ed.setSelection(invest_ed.getText().toString().length());
			}
			break;
		case R.id.financial_agreement_tv2: // 购买历程
			intent = new Intent(this, KKDWebActivity.class);
			intent.putExtra("url", Environment.getH5Url() + "kplandebt.html");
			startActivity(intent);
			break;
		case R.id.recharge: // 充值
			SystemUtils.onEvent("Regular_BidPage_Recharge", 1);
			if (PreferenceUtils.getInstance().getAutonym(this) == 1) {
				if (PreferenceUtils.getInstance().getBoundBankCard(this) == 1) {
					intent = new Intent(this, RechargeActivity.class);
					startActivity(intent);
				} else {
					intent = new Intent(this, ForTenderActivity.class);
					intent.putExtra("enterTypeFlag", 0);
					startActivity(intent);
				}
			} else {
				intent = new Intent(this, ForTenderActivity.class);
				intent.putExtra("enterTypeFlag", 4);
				startActivity(intent);
			}
			break;
		case R.id.frozen_popup: // icon
			showTipPopupwindow(frozen_img, "为购买时您实际赚得的收益+折让总价，不含购买债权时您垫付转让人的利息");
			break;
		}

	}

	/***
	 * 输入框处理
	 */
	public void inputProcessing() {
		invest_ed.setFinanceEditListener(new onFinanceEditListener() {

			@Override
			public void onValueChanged(double toValue, double fromValue) {
				// 购买金额
				buyamount_tv.setText(df.format(data.getPerAmount() * 0.01
						* toValue));
				// 预计赚得收益
				double principal = data.getPerPrincipal() * toValue;
				double income = principal + principal * data.getLeftTerm()
						/ 12.0 * (data.getPreYearRate() / 10000.0) + principal
						* data.getLeftTerm() / 12.0
						* (data.getActivityRate() / 10000.0);
				double shouyi = income - data.getPerPrice() * toValue;
				estimate_tv.setText(df.format((long) shouyi * 0.01));
				if (toValue > 0) {
					next_bt.setEnabled(true);
					next_bt.setClickable(true);
				} else {
					next_bt.setEnabled(false);
					next_bt.setClickable(false);
				}
			}

			@Override
			public void onOutLimit() {

			}

			@Override
			public void afterValueChanged(double toValue) {

			}
		});
	}

	/*****
	 * 投标
	 */
	public void tender() {
		if (mAccountInfo != null && mAccountInfo.getWithholdAuth() != null) { // 新浪充值
			if (mAccountInfo.getWithholdAuth().getWithdrawStatus() == 1
					&& mAccountInfo.getWithholdAuth().getIsWithholdAuth() == 0) {
				showSinaDialog();
			} else {
				if (yourCreditIsRunningLow()) {
					showNotSufficientFundsDialog();
				} else {
					transferTenderAffirm();
				}
			}
		}
	}

	// 余额不足
	public boolean yourCreditIsRunningLow() {

		if (balance >= Double.parseDouble(buyamount_tv.getText().toString())) {
			return false;
		} else {
			return true;
		}

	}

	/**
	 * 投标接口
	 */
	public void transferTenderAffirm() {
		showTenderToLoadDialog("购买 " + invest_ed.getText().toString() + "份",
				loading);
		KkdHttpMagager.getInstance().transferTenderAffirm(
				Integer.parseInt(invest_ed.getText().toString()),
				data.getTransferId(), String.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						String str = responseBody.toString();
						Message msg = new Message();
						msg.what = TENDER_CODE_ZERO;
						msg.obj = str;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.what = TENDER_CODE_ELSE;
						msg.obj = desc;
						mHandler.sendMessage(msg);
					}
				});

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (PreferenceUtils.getInstance().getLogin(this) == 0) {
			getAccountInfo();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == KKDSinaWebActivity.SET_PWD) {
			if (resultCode == KKDSinaWebActivity.SET_PWD_SUCCESS) {

			} else {
				showSinaDialog();
			}
		} else if (requestCode == TENDER_REQUESTCODE) {
			if (resultCode == CreditorIsRightsTenderAffirmSuccessActivity.CLOSE_CODE) { // 成功页关闭
				finish();
			} else if (resultCode == CreditorIsRightsTenderAffirmSuccessActivity.CONTINUE_TO_BUY) { // 继续购买
				requestParticulars();
			} else if (resultCode == CreditorIsRightsTenderAffirmSuccessActivity.TOENJOY_CLOSE_RESULT_CODE) { // 快快享福投标摇奖返回结果码
				finish();
			}
		}
	}

	/**
	 * 
	 * 查询账户余额
	 */
	public void getAccountInfo() {

		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		loadDialog = DialogUtils.toLoadDialog(this, "加载中...");
		KkdHttpMagager.getInstance().getAccountInfoManager(
				AccountInfoRes.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						mAccountInfo = (AccountInfoRes) responseBody;

						balance = mAccountInfo.getBalance();// .getDouble("balance");
						mHandler.sendEmptyMessage(ACCOUNTINFO_CODE_ZERO);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.what = ACCOUNTINFO_CODE_ELSE;
						msg.obj = desc;
						mHandler.sendMessage(msg);
					}
				});
	}

	/*****************
	 * 请求定期详情接口
	 ****************/
	public void requestParticulars() {
		KkdHttpMagager.getInstance().BondTransferParticulars(
				data.getTransferId(), BondTransferParData.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						BondTransferParData data = (BondTransferParData) responseBody;
						Message msg = new Message();
						msg.what = PARTICULARS_CODE_ZERO;
						msg.obj = data;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.what = PARTICULARS_CODE_ELSE;
						msg.obj = desc;
						mHandler.sendMessage(msg);
					}
				});
	}

	/****** 账户余额不足对话框 ************/
	public void showNotSufficientFundsDialog() {
		if (nsfDialog != null) {
			nsfDialog.cancel();
			nsfDialog = null;
		}
		nsfDialog = DialogUtils.notSufficientFundsDialog(this,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						switch (v.getId()) {
						case R.id.cancel_tv: // 取消
							nsfDialog.dismiss();
							break;
						case R.id.recharge_tv: // 充值

							SystemUtils.onEvent(
									"Regular_BidPage_Windows_Recharge", 1);
							AuthenticationUtils.getAuthenticationResult(
									CreditorIsRightsTenderAffirmActivity.this,
									3, RechargeActivity.class);
							nsfDialog.dismiss();
							break;
						}

					}
				}, true);
		nsfDialog.show();
	}

	protected void showSinaDialog() {
		if (mSinaDialog != null) {
			mSinaDialog.cancel();
			mSinaDialog = null;
		}
		try {
			String text = "";

			if (mAccountInfo.getWithholdAuth().getIsSinaPayPassword() == 0) {
				text = mAccountInfo.getWithholdAuth().getPayPasswordTips();
			} else if (mAccountInfo.getWithholdAuth().getIsWithholdAuth() == 0) {
				text = mAccountInfo.getWithholdAuth().getWithholdAuthTips();
			}
			if (!TextUtils.isEmpty(text)) {
				mSinaDialog = DialogUtils.generate2BDialog(this, text, "去设置",
						"再看看", new OnClickListener() {

							@Override
							public void onClick(View v) {
								mSinaDialog.dismiss();
								Intent intent = new Intent(
										CreditorIsRightsTenderAffirmActivity.this,
										KKDSinaWebActivity.class);
								intent.putExtra("url", mAccountInfo
										.getWithholdAuth()
										.getSinaWithholdAuthUrl());
								intent.putExtra("useTitleName", true);
								intent.putExtra("titleName", "新浪支付");
								startActivityForResult(intent,
										KKDSinaWebActivity.SET_PWD);
							}
						}, new OnClickListener() {

							@Override
							public void onClick(View v) {
								mSinaDialog.dismiss();
								finish();
							}
						});
				mSinaDialog.show();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	private void showTipPopupwindow(View targetView, String desc) {
		if (tip_popupWindow != null) {
			tip_popupWindow.dismiss();
			tip_popupWindow = null;
		}
		tip_popupWindow = DialogUtils
				.showTipPopupWindow(this, targetView, desc);
	}

	/***** 投标等待Dialog *********/
	public void showTenderToLoadDialog(String content, String loading) {
		if (tenderDialog != null) {
			tenderDialog.cancel();
			tenderDialog = null;
		}
		tenderDialog = DialogUtils.tendertoLoadDialog(this, content, loading);
		tenderDialog.show();
	}

	/******** 关闭投标等待Dialog ******/
	public void closeTenderToLoadDialog() {
		if (tenderDialog != null) {
			if (tenderDialog.isShowing())
				tenderDialog.dismiss();
			tenderDialog.cancel();
			tenderDialog = null;
		}
	}

	/********** 投标失败结果 ************/
	public void showTenderBeDefeatedResult(String desc) {
		beDefeatedDialog = DialogUtils.tenderBeDefeatedResult(this, desc,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						beDefeatedDialog.dismiss();
					}
				});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		if (mSinaDialog != null) {
			mSinaDialog.cancel();
			mSinaDialog = null;
		}
		/***** 投标等待Dialog *********/
		if (tenderDialog != null) {
			tenderDialog.cancel();
			tenderDialog = null;
		}
		/********** 投标失败结果 ************/
		if (beDefeatedDialog != null) {
			beDefeatedDialog.cancel();
			beDefeatedDialog = null;
		}
		if (tip_popupWindow != null) {
			tip_popupWindow.dismiss();
			tip_popupWindow = null;
		}
	}

}
